package com.probox.common.entity.service.platfom.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.probox.common.core.enums.DataStatus;
import com.probox.common.core.enums.PageTypeEnum;
import com.probox.common.core.utils.DateUtils;
import com.probox.common.core.utils.SecurityUtils;
import com.probox.common.core.utils.StringUtils;
import com.probox.common.entity.domain.platfom.PlatformPageConfigComponent;
import com.probox.common.entity.domain.platfom.vo.UseTypeVo;
import com.probox.common.entity.domain.platfom.vo.api.PlatformComponentDataVo;
import com.probox.common.entity.domain.platfom.vo.api.PlatformComponentVo;
import com.probox.common.entity.domain.platfom.vo.api.PlatformPageVo;
import com.probox.common.entity.domain.platfom.vo.api.PlatformTemplateView;
import com.probox.common.entity.mapper.platfom.PlatformPageConfigComponentMapper;
import com.probox.common.entity.service.platfom.IPlatformPageConfigComponentService;
import com.probox.common.entity.service.platfom.IPlatformPageConfigDataService;
import com.probox.common.redis.service.RedisService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;

/**
 * 页面组件信息Service业务层处理
 *
 * @date 2021-06-10
 */
@Service
@Transactional
public class PlatformPageConfigComponentServiceImpl extends ServiceImpl<PlatformPageConfigComponentMapper, PlatformPageConfigComponent> implements IPlatformPageConfigComponentService {
    @Autowired
    private PlatformPageConfigComponentMapper platformPageConfigComponentMapper;

    @Autowired
    private IPlatformPageConfigDataService platformPageConfigDataServicel;

    @Autowired
    private RedisService redisService;

    /**
     * 查询页面组件信息
     *
     * @param componentUid 页面组件信息ID
     * @return 页面组件信息
     */
    @Override
    public PlatformPageConfigComponent selectPlatformPageConfigComponentById(Long componentUid) {
        return this.getById(componentUid);
    }

    /**
     * 查询页面组件信息列表
     *
     * @param platformPageConfigComponent 页面组件信息
     * @return 页面组件信息
     */
    @Override
    public List<PlatformPageConfigComponent> queryList(PlatformPageConfigComponent platformPageConfigComponent) {
        QueryWrapper<PlatformPageConfigComponent> queryWrapper = Wrappers.query();
        if (StringUtils.isNotEmpty(String.valueOf(platformPageConfigComponent.getPageUid())) && platformPageConfigComponent.getPageUid() != null) {
            queryWrapper.eq("PAGE_UID", platformPageConfigComponent.getPageUid());
        }
        if (StringUtils.isNotEmpty(String.valueOf(platformPageConfigComponent.getDataStatus())) && platformPageConfigComponent.getDataStatus() != null) {
            queryWrapper.eq("DATA_STATUS", platformPageConfigComponent.getDataStatus());
        }
        queryWrapper.orderByAsc("DATA_SORT");

        return platformPageConfigComponentMapper.selectList(queryWrapper);
    }

    /**
     * 新增页面组件信息
     *
     * @return 结果
     */
    @Override
    public String insertPlatformPageConfigComponent() {
        PlatformPageConfigComponent platformPageConfigComponent = new PlatformPageConfigComponent();
        platformPageConfigComponent.setComponentUid(newUid());
        platformPageConfigComponent.setCreateName(SecurityUtils.getUsername());
        platformPageConfigComponent.setCreateUid(SecurityUtils.getUserId());
        platformPageConfigComponent.setCreateTime(DateUtil.date());
        platformPageConfigComponent.setDataStatus(DataStatus.delete.getKey());
        platformPageConfigComponentMapper.save(platformPageConfigComponent);
        return platformPageConfigComponent.getComponentUid();
    }

    /**
     * 新增页面组件信息
     *
     * @param platformTemplateView 模板信息
     * @param vo                   模板页面vo信息
     * @return
     */
    @Override
    public void insertPlatformPageConfigComponent(PlatformTemplateView platformTemplateView, PlatformPageVo vo) {
        List<PlatformComponentVo> component = vo.getComponent();
        //if (ObjectUtil.isEmpty(component)) throw new PlatformException("模板组件添加失败");
        if (ObjectUtil.isNotEmpty(component)) {
            component.forEach(voCompent -> {
                PlatformPageConfigComponent save = save(platformTemplateView, vo, voCompent);
                platformPageConfigDataServicel.insertPlatformPageConfigData(platformTemplateView, voCompent);
            });
        }
    }

    /**
     * 复制组件信息数据
     *
     * @param view
     * @param pageUid
     * @param copyPageUid 复制给谁的
     */
    @Override
    public void copyPlatformPageConfigComponent(PlatformTemplateView view, Long pageUid, Long copyPageUid) {
        PlatformPageConfigComponent platformPageConfigComponent = new PlatformPageConfigComponent();
        platformPageConfigComponent.setDataStatus(DataStatus.valid.getKey());
        platformPageConfigComponent.setPageUid(pageUid);
        int index = 0;
        if (ObjectUtil.isNotEmpty(view.getIsCopy())) {
            index = 1;
        }
        List<PlatformPageConfigComponent> platformPageConfigComponents = this.queryList(platformPageConfigComponent);
        if (ObjectUtil.isNotEmpty(platformPageConfigComponents)) {
            int finalIndex = index;
            platformPageConfigComponents.forEach(component -> {
                component.setPageUid(copyPageUid);
                PlatformPageConfigComponent save = saveCopy(view, component);
                if (finalIndex == 1) {
                    platformPageConfigDataServicel.copyPlatformPageConfigData(view, component.getComponentUid(), save.getComponentUid());
                }
            });
        }
    }

    /**
     * 获取信息vo
     *
     * @param pageUid
     * @return
     */
    @Override
    public List<PlatformComponentVo> getComponentVoList(Long pageUid, Long uid, UseTypeVo useTypeVo) {
        PlatformPageConfigComponent platformPageConfigComponent = new PlatformPageConfigComponent();
        platformPageConfigComponent.setDataStatus(DataStatus.valid.getKey());
        platformPageConfigComponent.setPageUid(pageUid);
        List<PlatformPageConfigComponent> platformPageConfigComponents = this.queryList(platformPageConfigComponent);
        List<PlatformComponentVo> list = new ArrayList<>();
        if (ObjectUtil.isNotEmpty(platformPageConfigComponents)) {
            platformPageConfigComponents.forEach(component -> {
                PlatformComponentVo componentVo = new PlatformComponentVo();
                BeanUtils.copyProperties(component, componentVo);
                // 如果数据已下架或者是被删除则不返回给前端
                List<PlatformComponentDataVo> dataVo = platformPageConfigDataServicel.getDataVo(componentVo.getComponentUid(), componentVo.getLimitsNumber(), uid, useTypeVo, component.getSourceComponentUid());
                //if (!ObjectUtil.isEmpty(dataVo)) {
                    componentVo.setData(dataVo);
                    list.add(componentVo);
                //}
                // platformPageConfigDataServicel.copyPlatformPageConfigData(view, save.getComponentUid());
            });
        }
        return list;
    }

    @Override
    public List<PlatformComponentVo> getComponentVoList(Long pageUid, Long uid) {
        PlatformPageConfigComponent platformPageConfigComponent = new PlatformPageConfigComponent();
        platformPageConfigComponent.setDataStatus(DataStatus.valid.getKey());
        platformPageConfigComponent.setPageUid(pageUid);
        List<PlatformPageConfigComponent> platformPageConfigComponents = this.queryList(platformPageConfigComponent);
        List<PlatformComponentVo> list = new ArrayList<>();
        if (ObjectUtil.isNotEmpty(platformPageConfigComponents)) {
            platformPageConfigComponents.forEach(component -> {
                PlatformComponentVo componentVo = new PlatformComponentVo();
                BeanUtils.copyProperties(component, componentVo);
                //componentVo.setData(platformPageConfigDataServicel.getDataVo(componentVo.getComponentUid(), componentVo.getLimitsNumber(), uid,useTypeVo,component.getSourceComponentUid()));
                list.add(componentVo);
                // platformPageConfigDataServicel.copyPlatformPageConfigData(view, save.getComponentUid());
            });
        }
        return list;
    }


    /**
     * 修改组件信息
     *
     * @param platformTemplateView
     * @param vo
     */
    @Override
    public void updatePlatformPageConfigComponent(PlatformTemplateView platformTemplateView, PlatformPageVo vo) {
        List<PlatformComponentVo> component = vo.getComponent();
        removeComponent(vo.getPageUid());
        //if (ObjectUtil.isEmpty(component)) throw new PlatformException("模板组件添加失败");
        if (ObjectUtil.isNotEmpty(component)) {
            component.forEach(voCompent -> {
                if (ObjectUtil.isEmpty(voCompent.getComponentUid())) {
                    PlatformPageConfigComponent save = save(platformTemplateView, vo, voCompent, null);
                    voCompent.setComponentUid(save.getComponentUid());
                    platformPageConfigDataServicel.insertPlatformPageConfigData(platformTemplateView, voCompent);
                } else {
                    edit(platformTemplateView, vo, voCompent);
                    platformPageConfigDataServicel.updatePlatformPageConfigData(platformTemplateView, voCompent);
                }
            });
        }
    }

    /**
     * 批量删除页面组件信息
     *
     * @param componentUids 需要删除的页面组件信息ID
     * @return 结果
     */
    @Override
    public boolean deletePlatformPageConfigComponentByIds(Long[] componentUids) {
        return this.removeByIds(Arrays.asList(componentUids));
    }

    public void removeComponent(Long pageUid) {
        UpdateWrapper<PlatformPageConfigComponent> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("PAGE_UID", pageUid);
        updateWrapper.set("DATA_STATUS", DataStatus.delete.getKey());
        updateWrapper.set("UPDATE_UID", SecurityUtils.getUserId());
        updateWrapper.set("UPDATE_NAME", SecurityUtils.getUsername());
        updateWrapper.set("UPDATE_TIME", DateUtil.date());
        this.update(updateWrapper);
    }

    private String newUid() {
        String time = DateUtils.getDateT();
        String key = "YR" + time;
        String no = String.valueOf(redisService.incr(key, 60));
        try {
        } catch (Exception e) {
            no = String.valueOf(new Random().nextLong());
            e.printStackTrace();
        }
        while (no.length() < 4) {
            no = "0" + no;
        }
        return key + no;
    }

    /**
     * 添加组件信息
     *
     * @param view
     * @param voPage
     * @param vo
     * @return
     */
    private PlatformPageConfigComponent save(PlatformTemplateView view, PlatformPageVo voPage, PlatformComponentVo vo, PlatformPageConfigComponent component) {
        PlatformPageConfigComponent configComponent = new PlatformPageConfigComponent();
        //if (ObjectUtil.isEmpty(vo)) throw new PlatformException("模板组件信息有误,请重试添加!");
        if (ObjectUtil.isEmpty(component)) {
            BeanUtils.copyProperties(vo, configComponent);
            configComponent.setPageUid(voPage.getPageUid());
            if ((!PageTypeEnum.homePage.getKey().equals(voPage.getPageType()) || !PageTypeEnum.proPage.getKey().equals(voPage.getPageType())) && ObjectUtil.isEmpty(configComponent.getComponentUid())) {
                configComponent.setComponentUid(newUid());
            }
        } else {
            BeanUtils.copyProperties(component, configComponent);
            configComponent.setComponentUid(newUid());
        }
        configComponent.setCreateName(view.getUserName());
        configComponent.setCreateUid(view.getUserId());
        configComponent.setCreateTime(view.getTime());
        configComponent.setUpdateName(view.getUserName());
        configComponent.setUpdateUid(view.getUserId());
        configComponent.setUpdateTime(view.getTime());
        configComponent.setDataStatus(DataStatus.valid.getKey());
        if (ObjectUtil.isEmpty(component)) {
            platformPageConfigComponentMapper.saveAll(configComponent);
        } else {
            this.updateById(configComponent);
        }
        return configComponent;
    }

    private PlatformPageConfigComponent save(PlatformTemplateView view, PlatformPageVo voPage, PlatformComponentVo vo) {
        PlatformPageConfigComponent configComponent = new PlatformPageConfigComponent();
        //if (ObjectUtil.isEmpty(vo)) throw new PlatformException("模板组件信息有误,请重试添加!");
        BeanUtils.copyProperties(vo, configComponent);
        configComponent.setPageUid(voPage.getPageUid());
        configComponent.setCreateName(view.getUserName());
        configComponent.setCreateUid(view.getUserId());
        configComponent.setCreateTime(view.getTime());
        configComponent.setUpdateName(view.getUserName());
        configComponent.setUpdateUid(view.getUserId());
        configComponent.setUpdateTime(view.getTime());
        configComponent.setDataStatus(DataStatus.valid.getKey());
        if ((!PageTypeEnum.homePage.getKey().equals(voPage.getPageType()) || !PageTypeEnum.proPage.getKey().equals(voPage.getPageType())) && ObjectUtil.isEmpty(configComponent.getComponentUid())) {
            configComponent.setComponentUid(newUid());
            platformPageConfigComponentMapper.saveAll(configComponent);
        } else {
            this.updateById(configComponent);
        }
        return configComponent;
    }

    /**
     * 复制数据
     *
     * @param view
     * @param component
     * @return
     */
    private PlatformPageConfigComponent saveCopy(PlatformTemplateView view, PlatformPageConfigComponent component) {
        PlatformPageConfigComponent configComponent = new PlatformPageConfigComponent();
        //if (ObjectUtil.isEmpty(vo)) throw new PlatformException("模板组件信息有误,请重试添加!");
        BeanUtils.copyProperties(component, configComponent);
        configComponent.setComponentUid(newUid());
        // 给来源id
        configComponent.setSourceComponentUid(component.getComponentUid());
        configComponent.setCreateName(view.getUserName());
        configComponent.setCreateUid(view.getUserId());
        configComponent.setCreateTime(view.getTime());
        configComponent.setUpdateName(view.getUserName());
        configComponent.setUpdateUid(view.getUserId());
        configComponent.setUpdateTime(view.getTime());
        configComponent.setDataStatus(DataStatus.valid.getKey());
        platformPageConfigComponentMapper.saveAllCopy(configComponent);

        return configComponent;
    }

    private PlatformPageConfigComponent edit(PlatformTemplateView view, PlatformPageVo voPage, PlatformComponentVo vo) {
        PlatformPageConfigComponent configComponent = new PlatformPageConfigComponent();
        //if (ObjectUtil.isEmpty(vo)) throw new PlatformException("模板组件信息有误,请重试添加!");
        BeanUtils.copyProperties(vo, configComponent);
        if ((!PageTypeEnum.homePage.getKey().equals(voPage.getPageType()) || !PageTypeEnum.proPage.getKey().equals(voPage.getPageType())) && ObjectUtil.isEmpty(configComponent.getComponentUid())) {
            configComponent.setComponentUid(newUid());
        }
        configComponent.setPageUid(voPage.getPageUid());
        configComponent.setUpdateName(view.getUserName());
        configComponent.setUpdateUid(view.getUserId());
        configComponent.setUpdateTime(view.getTime());
        configComponent.setDataStatus(DataStatus.valid.getKey());
        this.updateById(configComponent);
        return configComponent;
    }

}
